package com.example.myserver.util;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

public final class CommonUtils {

    private CommonUtils() {
    }

    /**
     * 创建 ID 值
     *
     * @return {String} ID值
     */
    public static String createId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 格式化当前日期
     */
    public static String formatCurrentTime() {
        final LocalDateTime dateTime = LocalDateTime.now();
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        return dateTime.format(formatter);
    }
    
    /**
     * 格式化当前年月日
     */
    public static String formatCurrentDate() {
        final LocalDateTime dateTime = LocalDateTime.now();
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        return dateTime.format(formatter);
    }
    

    /**
     * 将 LocalDateTime 转为 LocalDate
     */
    public static LocalDate timeToDate(final LocalDateTime time) {
        if (Objects.isNull(time)) {
            return null;
        }

        return time.toLocalDate();
    }

    public static LocalDateTime dateToLocalDateTIme(final Date time) {
        if (Objects.isNull(time)) {
            return null;
        }
        final Instant instant = time.toInstant();
        // 使用系统默认时区将 Instant 转换为 LocalDateTime
        final LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        return localDateTime;
    }
    
    public static Date localDateTimeToDate(final LocalDateTime time) {
        if (Objects.isNull(time)) {
            return null;
        }
        final Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
        return  date;
    }

}
